package com.qfhd.soft.cjzcore.TaskCenter.CSJ;

import android.app.Activity;
import android.content.Context;
import android.os.Message;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.MainThread;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTSplashAd;
import com.qfhd.soft.cjzcore.Core.CJLogger;
import com.qfhd.soft.cjzcore.Core.CJScreenUtil;
import com.qfhd.soft.cjzcore.Listener.CJLoadFinishListener;
import com.qfhd.soft.cjzcore.TaskCenter.TTAdManagerHolder;
import com.qfhd.soft.cjzcore.TaskCenter.WeakHandler;

public class CJCSJ_Splash implements WeakHandler.IHandler{

    //开屏广告加载发生超时但是SDK没有及时回调结果的时候，做的一层保护。
    private WeakHandler mHandler = new WeakHandler(this);
    //开屏广告加载超时时间,建议大于3000,这里为了冷启动第一次加载到广告并且展示,示例设置了3000ms
    private static final int AD_TIME_OUT = 3000;
    private static final int MSG_GO_MAIN = 1;
    //开屏广告是否已经加载
    private boolean mHasLoaded;
    private TTAdNative mTTAdNative;

    private CJLoadFinishListener overListener;

    private static CJCSJ_Splash cjcsj_splash;
    public static CJCSJ_Splash getInstance(){
        if(cjcsj_splash == null){
            synchronized (CJCSJ_Splash.class){
                cjcsj_splash = new CJCSJ_Splash();
            }
        }
        return cjcsj_splash;
    }

    public void begin(Activity activity, FrameLayout adContainer, CJLoadFinishListener overListener) {
        //step2:创建TTAdNative对象
        mTTAdNative = TTAdManagerHolder.get().createAdNative(activity.getApplicationContext());
        //在合适的时机申请权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题
        //在开屏时候申请不太合适，因为该页面倒计时结束或者请求超时会跳转，在该页面申请权限，体验不好
        // TTAdManagerHolder.getInstance(this).requestPermissionIfNecessary(this);
        //定时，AD_TIME_OUT时间到时执行，如果开屏广告没有加载则跳转到主页面
        mHandler.sendEmptyMessageDelayed(MSG_GO_MAIN, AD_TIME_OUT);
        this.overListener = overListener;
        //step3:创建开屏广告请求参数AdSlot,具体参数含义参考文档
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(CJCSJsdk.SplashId)
                .setSupportDeepLink(true)
                .setImageAcceptedSize((int)CJScreenUtil.getScreenWidthDp(activity), (int) CJScreenUtil.getHeight(activity))
                .build();
        //step4:请求广告，调用开屏广告异步请求接口，对请求回调的广告作渲染处理
        mTTAdNative.loadSplashAd(adSlot, new TTAdNative.SplashAdListener() {
            @Override
            @MainThread
            public void onError(int code, String message) {
                CJLogger.v(message);
                mHasLoaded = true;
                next();
            }

            @Override
            @MainThread
            public void onTimeout() {
                mHasLoaded = true;
                next();
            }

            @Override
            @MainThread
            public void onSplashAdLoad(TTSplashAd ad) {
                CJLogger.v("onSplashAdLoad");
                mHasLoaded = true;
                mHandler.removeCallbacksAndMessages(null);
                if (ad == null) {
                    return;
                }
                //获取SplashView
                View view = ad.getSplashView();
                if (view != null) {
                    adContainer.removeAllViews();
                    //把SplashView 添加到ViewGroup中,注意开屏广告view：width >=70%屏幕宽；height >=50%屏幕高
                    adContainer.addView(view);
                    //设置不开启开屏广告倒计时功能以及不显示跳过按钮,如果这么设置，您需要自定义倒计时逻辑
//                    ad.setNotAllowSdkCountdown();
                } else {
                    CJLogger.v("ad.getSplashView failed");
                    next();
                }

                //设置SplashView的交互监听器
                ad.setSplashInteractionListener(new TTSplashAd.AdInteractionListener() {
                    @Override
                    public void onAdClicked(View view, int type) {
//                        Log.d(TAG, "onAdClicked");
//                        showToast("开屏广告点击");
                    }

                    @Override
                    public void onAdShow(View view, int type) {
//                        Log.d(TAG, "onAdShow");
//                        showToast("开屏广告展示");
                        CJLogger.v("onAdShow");
                    }

                    @Override
                    public void onAdSkip() {
//                        Log.d(TAG, "onAdSkip");
//                        showToast("开屏广告跳过");
                        CJLogger.v("onAdSkip");
                        next();

                    }

                    @Override
                    public void onAdTimeOver() {
//                        Log.d(TAG, "onAdTimeOver");
//                        showToast("开屏广告倒计时结束");
                        CJLogger.v("onAdTimeOver");
                        next();
                    }
                });
                if (ad.getInteractionType() == TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
                    ad.setDownloadListener(new TTAppDownloadListener() {
                        boolean hasShow = false;

                        @Override
                        public void onIdle() {

                        }

                        @Override
                        public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
                            if (!hasShow) {
//                                showToast("下载中...");
                                hasShow = true;
                            }
                        }

                        @Override
                        public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
//                            showToast("下载暂停...");
                        }

                        @Override
                        public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
//                            showToast("下载失败...");

                        }

                        @Override
                        public void onDownloadFinished(long totalBytes, String fileName, String appName) {

                        }

                        @Override
                        public void onInstalled(String fileName, String appName) {

                        }
                    });
                }
            }
        }, AD_TIME_OUT);

    }

    private void next(){
        if(overListener != null){
            overListener.loadFinish(null);
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    public void handleMsg(Message msg) {
        if (msg.what == MSG_GO_MAIN) {
            if (!mHasLoaded) {
//                showToast("广告已超时，跳到主页面");
                CJLogger.v("广告已超时，跳到主页面");
                next();
            }
        }
    }
}
